package cn.client.ui.view.signIn

import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.VisualTransformation
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavController
import cn.client.MainViewModel
import cn.client.R
import cn.client.navigation.destinations.AppStart
import cn.client.navigation.destinations.Myself
import cn.client.navigation.destinations.Overview
import cn.client.navigation.destinations.SignInSecond
import kotlinx.coroutines.launch


/**
 * 登录：第二步
 */
@Composable
fun SignInSecondPage (
    account: String,
    navController: NavController,
    viewModel: SignInViewModel = hiltViewModel(),
    ) {
    val context = LocalContext.current
    var password: String by remember { mutableStateOf("") }
    var passwordHidden by remember{ mutableStateOf(true)}  // 默认隐藏
    val coroutineScope = rememberCoroutineScope()

//    val mainViewModel: MainViewModel = hiltViewModel()

    //  使用LaunchedEffect来启动协程，收集事件
    LaunchedEffect(Unit){
        viewModel.pageEvents.collect {
            if (it is SignInViewModel.PageEvent.LoginRes){
                val userId = it.loginRes.data?.uid
                Log.d("登录事件","登录的账号为：$account 响应码：${it.loginRes.code} 返回信息：${it.loginRes.msg}")
                if (it.loginRes.code == 200){
                    // 发送连接意图
                    Toast.makeText(context,"登录成功", Toast.LENGTH_SHORT).show()
                    // 查询数据库，如果数据保存成功再跳转页面
                    navController.navigate(Overview.route) {
                        // 添加popUpTo，将AppStart从回退栈中移除
                        popUpTo(AppStart.route) {
                            // 包含当前的目的地，防止在跳转回时再次调用该操作
                            inclusive = true
                        }
                        // 清空回退栈
                        launchSingleTop = true
                    }
                } else {
                    Toast.makeText(context,"密码错误", Toast.LENGTH_LONG).show()
                }
            } else if (it is SignInViewModel.PageEvent.Error){
                Toast.makeText(context,"未知错误：${it.error}", Toast.LENGTH_LONG).show()
            }
        }
    }

    Box(
        contentAlignment = Alignment.Center,
        modifier = Modifier
            .background(Color.White)
    ) {
        Column(
            modifier = Modifier
        ) {
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(40.dp))
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .wrapContentSize(Alignment.Center, false)
            ) {
                Text(
                    text = (stringResource(R.string.sign_in)),
                    fontSize = 30.sp, // 字体大小
                    fontWeight = FontWeight.Bold,
                    textAlign = TextAlign.Center,
                )
            }
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(30.dp))
            /* 输入密码 */
            Row(
                modifier = Modifier
            ) {
                OutlinedTextField(
                    value = password,
                    label = {  Text(stringResource(R.string.password)) },
                    onValueChange = { str -> password = str },
                    placeholder = { Text(stringResource(R.string.input_pwd)) },
                    singleLine = true,
                    trailingIcon = {
                        IconButton(
                            onClick = { passwordHidden = !passwordHidden }
                        ) {
                            if (passwordHidden){
                                Icon(painterResource(id = R.drawable.ic_preview_close_one), null)
                            } else {
                                Icon(painterResource(id = R.drawable.ic_preview_open), null)
                            }
                        }
                    },
                    visualTransformation = if (passwordHidden) PasswordVisualTransformation() else VisualTransformation.None,
                    modifier = Modifier
                        .clip(RoundedCornerShape(20.dp))
                        .fillMaxWidth()
                        .padding(10.dp)
                )
            }
            /* 间隔距离 */
            Spacer(modifier = Modifier.height(20.dp))
            /* 完成 */
            Button(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(10.dp),
                onClick = {
                // 发送意图
                    if (password != ""){
                        coroutineScope.launch {
                            viewModel.dispatch(SignInViewModel.PageIntent.VerifyPwd(account,password))
                        }
                    } else {
                        // 如果输入的内容为空，弹窗提示
                        Toast.makeText(context,"密码不能为空", Toast.LENGTH_LONG).show()
                    }
            }) {
                Text(
                    text = "完  成",
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Center
                )
            }
        }
    }
}